using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Reflection;
using System.Net;

namespace blogapi
{
    public partial class nastaveni : Form
    {
        public nastaveni(Form1 hlavniform)
        {
            nastavdefault();
            hlform = hlavniform;
            prvnispusteni = true;

            if (File.Exists(nachazitese+"/data.xml"))
            {
                XmlTextReader ctat = null;
                try
                {
                    typzapisu = 1;
                    ctat = new XmlTextReader(nachazitese+"/data.xml");
                    while (!ctat.EOF)
                    {
                        if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "options")
                        {
                            while (!ctat.EOF)
                            {
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "readtype")
                                {
                                    typzapisu = ctat.ReadElementContentAsInt();
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "autodelete")
                                {
                                    automazat = Convert.ToBoolean(ctat.ReadElementContentAsString());
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "encription")
                                {
                                    sifrovani = Convert.ToBoolean(ctat.ReadElementContentAsString());
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "debugmode")
                                {
                                    debugmode = Convert.ToBoolean(ctat.ReadElementContentAsString());
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "autobr")
                                {
                                    autobr = Convert.ToBoolean(ctat.ReadElementContentAsString());
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "question")
                                {
                                    dotazovatse = Convert.ToBoolean(ctat.ReadElementContentAsString());
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "autocatsdown")
                                {
                                    autokatdown = Convert.ToBoolean(ctat.ReadElementContentAsString());
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.Element && ctat.Name == "language")
                                {
                                    language = CultureInfo.CreateSpecificCulture(ctat.ReadElementContentAsString());
                                    continue;
                                }
                                if (ctat.MoveToContent() == XmlNodeType.EndElement && ctat.Name == "options")
                                {
                                    break;
                                }
                                ctat.Read();
                            }
                            break;
                        }
                        else
                            ctat.Read();
                    }
                }
                catch
                {
                    MessageBox.Show(getlang("chyba_nacitani"), getlang("chyba_nacitani_titulek"));
                }
                if (ctat != null)
                {
                    ctat.Close();
                }
                prvnispusteni = false;
            }
                if (File.Exists(nachazitese+"/nastaveni.db"))
                {
                    FileStream ctid = null;
                    BinaryReader read = null;
                    try
                    {
                        ctid = new FileStream(nachazitese+"/nastaveni.db", FileMode.Open);
                        read = new BinaryReader(ctid, Encoding.UTF8);
                        typzapisu = read.ReadInt32();
                        debugmode = read.ReadBoolean();
                        automazat = read.ReadBoolean();
                        autobr = read.ReadBoolean();
                        dotazovatse = read.ReadBoolean();
                        autokatdown = read.ReadBoolean();
                        sifrovani = read.ReadBoolean();
                        language = CultureInfo.CreateSpecificCulture(read.ReadString());
                        read.Close();
                        ctid.Close();
                    }
                    catch
                    {
                        MessageBox.Show(getlang("chyba_nacitani"), getlang("chyba_nacitani_titulek"));
                    }
                    prvnispusteni = false;
                }


            InitializeComponent();
            refreshlang();
            generuj();
        }

        private ResourceManager rm=null;
        public string getlang(string nazev)
        {
            if(rm==null)
            {
                if (File.Exists(nachazitese + "/lang/lang.resources"))
                {
                    rm = ResourceManager.CreateFileBasedResourceManager("lang", nachazitese + "\\lang", null);
                }
                else
                {
                    rm = new ResourceManager("blogapi.lang.lang", typeof(Form1).Assembly);
                }
            }
            return rm.GetString(nazev, language);
        }

        public void nastavdefault()
        {
            typzapisu = 1;
            debugmode = false;
            automazat = true;
            autobr = true;
            autokatdown = false;
            sifrovani = true;
            dotazovatse = true;
            language = CultureInfo.CurrentUICulture;
            FileInfo inff = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            nachazitese = inff.DirectoryName;
        }

        public void generuj()
        {
            comboBox1.Items.Clear();
            int def = 0;
            if (Directory.Exists(nachazitese + "/lang") == true)
            {
                DirectoryInfo inf = new DirectoryInfo(nachazitese + "/lang");
                FileInfo[] fls = inf.GetFiles();
                for (int i = 0; i < fls.Length; i++)
                {
                    if (fls[i].Name.IndexOf("lang") != 0)
                    {
                        continue;
                    }
                    string orez = fls[i].Name.Remove(0, 5);
                    if (orez == "resources")
                    {
                        comboBox1.Items.Add("en-US");
                        def = comboBox1.Items.Count - 1;
                        if (language.Name == "en-US")
                        {
                            comboBox1.SelectedIndex = def;
                        }
                        continue;
                    }
                    int poz = orez.IndexOf(".resources");
                    if (poz == -1)
                    {
                        continue;
                    }
                    orez = orez.Remove(poz, 10);
                    comboBox1.Items.Add(orez);
                    if (language.Name == orez)
                    {
                        comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
                    }
                }
            }
            if(comboBox1.Items.Count==0)
            {
                comboBox1.Items.Add("en-US");
            }
            if (comboBox1.SelectedIndex == -1)
            {
                comboBox1.SelectedIndex = def;
            }

            comboBox2.SelectedIndex = typzapisu;
            checkBox1.Checked = automazat;
            checkBox2.Checked = autobr;
            checkBox3.Checked = dotazovatse;
            checkBox4.Checked = autokatdown;
            checkBox5.Checked = sifrovani;

            if (prvnispusteni)
            {
                menuItem1.Enabled = false;
                this.ControlBox = false;
            }
            else
            {
                menuItem1.Enabled = true;
                this.ControlBox = true;
            }
        }
        Form1 hlform;

        public int typzapisu;
        public bool prvnispusteni;
        public bool debugmode;
        public bool automazat;
        public bool autobr;
        public bool dotazovatse;
        public bool autokatdown;
        public string nachazitese;
        public CultureInfo language;
        public bool sifrovani;

        private void menuItem3_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void menuItem6_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show(getlang("dotazodstraneni"), getlang("dotazodstranenitit"), MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1))
            {
                try
                {
                    if (File.Exists(nachazitese+"/data.xml"))
                    {
                        File.Delete(nachazitese + "/data.xml");
                    }
                    if (File.Exists(nachazitese + "/nastaveni.db"))
                    {
                        File.Delete(nachazitese + "/nastaveni.db");
                    }
                    if (File.Exists(nachazitese + "/soubory.db"))
                    {
                        File.Delete(nachazitese + "/soubory.db");
                    }
                    if (File.Exists(nachazitese + "/ucty.db"))
                    {
                        File.Delete(nachazitese + "/ucty.db");
                    }
                }
                catch
                {
                    MessageBox.Show(getlang("chybamazani"),getlang("chybamazanitit"));
                }
            }
        }

        private void menuItem7_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show(getlang("vypnutibezulozeni"), getlang("ukonceniaplikace"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
            {
                Application.Exit();
            }
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            nastavdefault();
            generuj();
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            prvnispusteni = false;
            automazat = checkBox1.Checked;
            autobr = checkBox2.Checked;
            autokatdown = checkBox4.Checked;
            dotazovatse = checkBox3.Checked;
            typzapisu = comboBox2.SelectedIndex;
            try
            {
                language = CultureInfo.CreateSpecificCulture(comboBox1.Items[comboBox1.SelectedIndex].ToString());
            }
            catch
            {
            }
            sifrovani = checkBox5.Checked;


            hlform.refreshlang();
            hlform.uloz();
            hlform.Show();
            this.Hide();
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            autori aut = new autori(this);
            aut.ShowDialog();
            aut = null;
        }

        public void refreshlang()
        {
            menuItem1.Text = getlang("moznosti");
            menuItem3.Text = getlang("zpet");
            menuItem4.Text = getlang("resetnastaveni");
            menuItem6.Text = getlang("odstransoubory");
            menuItem7.Text = getlang("konecbezzmen");
            menuItem9.Text = getlang("autori");
            menuItem2.Text = getlang("uloznast");
            label1.Text = getlang("languagechose");
            label2.Text = getlang("savetype");
            label3.Text = getlang("publikovanipris");
            checkBox1.Text = getlang("smazatautomat");
            label4.Text = getlang("psanipris");
            checkBox2.Text = getlang("automatickyod");
            Text = "W - "+getlang("nastaveni");
            comboBox2.Items.Clear();
            comboBox2.Items.Add(getlang("zapisbin"));
            comboBox2.Items.Add(getlang("xml"));
            checkBox3.Text = getlang("pripojenicheck");
            checkBox4.Text = getlang("autokatdown");
            checkBox5.Text = getlang("sifrovani");
            menuItem10.Text = getlang("updatecheck");
        }

        Thread aktualizacnivlakno;

        private void menuItem10_Click(object sender, EventArgs e)
        {
            bool doitnow = false;
            if (dotazovatse)
            {
                    if (DialogResult.OK == MessageBox.Show(getlang("upozornenipripojeni"), getlang("upozorneni"), MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1))
                    {
                        doitnow = true;
                    }
            }
            else
            {
               doitnow = true;
            }
            if (doitnow)
            {
                //aktualizace
                MessageBox.Show(getlang("posledniverze"), getlang("update"));
                aktualizacnivlakno = new Thread(zkontrolujaktualizaci);
                aktualizacnivlakno.IsBackground = true;
                aktualizacnivlakno.Priority = ThreadPriority.Lowest;
                aktualizacnivlakno.Start();
            }
        }

        private void zkontrolujaktualizaci()
        {
            Assembly tahle = Assembly.GetExecutingAssembly();
            string verze = tahle.FullName.Substring(tahle.FullName.IndexOf("Version="));
            verze = verze.Remove(verze.IndexOf(','),verze.Length-verze.IndexOf(','));
            verze = verze.Remove(0, "Version=".Length);
            HttpWebRequest zadost = null;
            HttpWebResponse odpov = null;
            Stream vys = null;
            string ver = "";
            string odk="";
            try
            {
                zadost = (HttpWebRequest)WebRequest.Create("http://updatecheck.vit-stekly.cz/writer.txt");
                odpov = (HttpWebResponse)zadost.GetResponse();
                vys = odpov.GetResponseStream();
                StreamReader cti = new StreamReader(vys);
                ver = cti.ReadLine();
                odk = cti.ReadLine();
            }
            catch
            {
                if (odpov != null)
                {
                    odpov.Close();
                }
                if (vys != null)
                {
                    vys.Close();
                }
                MessageBox.Show(getlang("updatefailed"), getlang("update"));
                return;
            }
            finally
            {
                if (odpov != null)
                {
                    odpov.Close();
                }
                if (vys != null)
                {
                    vys.Close();
                }
            }
            Version verznew = new Version(ver);
            Version verakt = new Version(verze);
            ver = ver.Replace('.', '0');
            verze = verze.Replace('.', '0');
            if (Convert.ToInt32(ver) > Convert.ToInt32(verze))
            {
                MessageBox.Show(getlang("updatenovapred") + " " + verznew.ToString() + " " + getlang("updatenovaza") + " " + odk, getlang("update"));
                return;
            }
            MessageBox.Show(getlang("updateaktualni"), getlang("update"));
        }
    }
    
}